package com.cn.wechat.wechat.controller;


import com.cn.wechat.wechat.service.WeChatService;
import com.cn.wechat.wechat.utils.WeiXinSignUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;


/**
 * 微信公众号
 */
@RestController
@RequestMapping(value="/wechat")
public class WeixinCoreController {

    private static Logger logger = LoggerFactory.getLogger(WeixinCoreController.class);

    @Autowired
    WeiXinSignUtil weiXinSignUtil;

    @Autowired
    WeChatService weChatService;
    /**
     * @Description: 验证请求是否来自微信服务器
     * @Parameters: WeixinCoreController
     * @Return: 返回微信服务器发过来的验证字符
     * @Create Date:
     * @Version: V1.00
     * @author:来日可期
     */
    @GetMapping(value="/access")
    public String WeChatInterface(HttpServletRequest request)throws Exception {
        System.out.println("-------------验证微信服务号信息开始----------");
        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");


        logger.info("signature is :" + signature + "timestamp is" + timestamp + "nonce is :" + nonce);
        if (weiXinSignUtil.checkSignature(signature, timestamp, nonce)) {
            System.out.println("-----------验证微信服务号结束------------");
            return echostr;
        } else {
            System.out.println("-----------验证微信服务号ssss------------");

            // 此处可以实现其他逻辑
            logger.warn("不是微信服务器发过来的请求，请小心！");
            return null;
        }

    }

    @GetMapping(value="/test")
    public String test(){

        logger.info("2222222222");
        return "2222";
    }

    /**
     * 此处是处理微信服务器的消息转发的
     */
    @PostMapping(value = "/access")
    public String processMsg(HttpServletRequest request) {
        // 调用核心服务类接收处理请求
        return weChatService.processRequest(request);
    }
}
